<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    {% load static %}
    <script src="{% static 'js/jquery-3.7.1.min.js' %}"></script>
    <style>
        li{
            display:flex;
            align-items: center;
            border-bottom: 1px solid gray;
        }
        img{
            width:50px;
            border-radius: 50%;
        }
    </style>
</head>
<body>
{% include 'header.html' %}
<div>
    <h1>{{ new.title }}</h1>
    <hr>
    <img src="/media/{{ new.img }}">
    <p>
        {{ new.content }}
    </p>
</div>
{% csrf_token %}
<textarea cols="50" rows="10" class="content" placeholder="评论内容"></textarea>
<button class="send">发表</button>
<ul>
    {% for comment in comments %}
    <li>
        <div class="left">
            <img src="{{ comment.user.avatar.url }}">
        </div>
        <div class="right">
            <h3>{{ comment.user.username }}</h3>
            <p>{{ comment.content }}</p>
            <div>{{ comment.createDate }}</div>
        </div>
    </li>
    {% endfor %}
</ul>
</body>
<script>
    $(function(){
        $('.send').click(function (){
        content = $('.content').val() //评论内容
        token = $('input:hidden').val()
        //发送ajax
        $.post(`/newsm/comment/{{ new.id }}`,`content=${content}&csrfmiddlewaretoken=${token}`)
            .then(res=>{
                console.log(res)
                if (res.code==200){
                    $li = $(`<li>
                            <div class="left">
                                <img src="{{ request.user.avatar.url }}">
                            </div>
                            <div class="right">
                                <h3>{{ request.user.username }}</h3>
                                <p>${content}</p>
                                <div>${res.data.createDate}</div>
                            </div>
                        </li>`)
                    $('ul').prepend($li)  //最前面
                }
                alert(res.msg)
                $('.content').val('')
                }).catch(res =>{
                console.log(res)
            })
        })
    })
</script>
</html>